﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EpcTagLibrary.Pat
{
    public class GroupField
    {
        private GroupField m_Parent;
        private PatternField m_Pattern;
        private string m_Value;
        private IList<GroupField> m_Children = new List<GroupField>();
        private IList<EPC> m_Epcs = new List<EPC>();

        public GroupField(GroupField parent)
        {
            m_Parent = parent;
        }

        public GroupField Parent
        {
            get
            {
                return m_Parent;
            }
        }

        public PatternField Pattern
        {
            get
            {
                return m_Pattern;
            }
            set
            {
                m_Pattern = value;
            }
        }

        public string Value
        {
            get
            {
                return m_Value;
            }
            set
            {
                m_Value = value;
            }
        }

        public IList<GroupField> Children
        {
            get
            {
                return m_Children;
            }
        }

        public IList<EPC> Epcs
        {
            get
            {
                return m_Epcs;
            }
        }

        public void AddEpc(EPC epc)
        {
            m_Epcs.Add(epc);
        }

        public GroupField FindOrAddGroup(PatternField pat, string val)
        {
            foreach (GroupField Field in m_Children)
            {
                string FieldVal = Field.Value;
                if (FieldVal.ToUpper().Equals(val.ToUpper()))
                {
                    return Field;
                }
            }

            GroupField Result = new GroupField(this);
            Result.Value = val;
            Result.Pattern= pat;
            m_Children.Add(Result);

            return Result;
        }

        public override string ToString()
        {
            StringBuilder Result = new StringBuilder();

            Result.Append("GroupField {\n");
            Result.Append("parent=");
            if (Parent == null)
            {
                Result.Append("null");
            }
            else
            {
                Result.Append(Parent.Value);
            }
            Result.Append("\n,pattern=");
            Result.Append(Pattern);
            Result.Append("\n,val=");
            Result.Append(Value);
            Result.Append("\n,epcs=");
            Result.Append(Epcs);
            Result.Append("}");

            return Result.ToString();
        }
    }
}
